package com.youngking.guns.modular.projectinfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.youngking.guns.core.base.controller.BaseController;
import com.youngking.guns.core.log.LogObjectHolder;
import com.youngking.guns.core.util.Common;
import com.youngking.guns.core.util.ToolUtil;
import com.youngking.guns.modular.company.service.ICompanyService;
import com.youngking.guns.modular.projectinfo.service.IProjectinfoService;
import com.youngking.guns.modular.system.model.Notice;
import com.youngking.guns.modular.system.model.Projectinfo;
import com.youngking.guns.modular.system.model.Wxuserinfo;
import com.youngking.guns.modular.system.service.INoticeService;
import com.youngking.guns.modular.wxuserinfo.service.IWxuserinfoService;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.weixin4j.Weixin;
import org.weixin4j.WeixinException;
import org.weixin4j.WeixinUrlFilter;
import org.weixin4j.model.message.template.TemplateData;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2018-08-03 13:56:09
 */
@Controller
@RequestMapping("/app/projectinfo")
@PropertySource("classpath:/aliyun.properties")
public class ProjectinfoAppController extends BaseController {

    private String PREFIX = "/projectinfo/projectinfo/";

    @Autowired
    private IProjectinfoService projectinfoService;
    @Autowired
    private ICompanyService companyService;
    @Autowired
    private IWxuserinfoService wxuserinfoService;
    @Value("${accesskeyid}")
    private String accesskeyid;  //验证码发送key
    @Value("${accesskeysecret}")
    private String accesskeysecret;  //验证码秘钥

    /**
     * 获取未审核列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String begindata = mapTypes.getString("begindata");
        String enddata = mapTypes.getString("enddata");
        String address = mapTypes.getString("address");
        String status = mapTypes.getString("status");
        String condition = mapTypes.getString("condition");
        int page = Integer.parseInt(mapTypes.getString("page"));
        int limit = Integer.parseInt(mapTypes.getString("limit"));
        Map<String, Object> map = new HashMap<>();
        map.put("starttime", begindata);
        map.put("endtime", enddata);
        map.put("address", address);
        map.put("status", status);
        map.put("condition", condition);
        map.put("offset", (page - 1) * limit);
        map.put("limit", limit);
        return projectinfoService.getlist(map);
    }

    /**
     * 提交项目
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@RequestBody String simpleObject)  {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String projectname = mapTypes.getString("projectname");
        String address = mapTypes.getString("address");
        String addressdetail = mapTypes.getString("addressdetail");
        String contacter = mapTypes.getString("contacter");
        String phone = mapTypes.getString("phone");
        String conunit = mapTypes.getString("conunit");
        String totaluinit = mapTypes.getString("totaluinit");
        String overview = mapTypes.getString("overview");
        String viewmark = mapTypes.getString("viewmark");
        String quantity = mapTypes.getString("quantity");
        String isannex = mapTypes.getString("isannex");
        String projectremark = mapTypes.getString("projectremark");
        String submitterphone = mapTypes.getString("submitterphone");
        String bankcode = mapTypes.getString("bankcode");
        String bankname = mapTypes.getString("bankname");
        String cardholder = mapTypes.getString("cardholder");
        String alipay = mapTypes.getString("alipay");
        String alipayname = mapTypes.getString("alipayname");
        String wechat = mapTypes.getString("wechat");
        String customerid = mapTypes.getString("customerid");

        EntityWrapper ew = new EntityWrapper();
        ew.setEntity(new Projectinfo());
        ew.where("projectname  ={0}", projectname);
        Projectinfo projectinfoold = projectinfoService.selectOne(ew);

        if (projectinfoold != null) {
            return "项目已存在!";
        } else {
            Projectinfo projectinfo = new Projectinfo();
            if (ToolUtil.isNotEmpty(customerid)) {
                projectinfo.setCustomerid(Integer.parseInt(customerid));
            }
            if (ToolUtil.isNotEmpty(projectname)) {
                projectinfo.setProjectname(projectname);
            }
            if (ToolUtil.isNotEmpty(address)) {
                projectinfo.setAddress(address);
            }
            if (ToolUtil.isNotEmpty(addressdetail)) {
                projectinfo.setAddressdetail(addressdetail);
            }
            if (ToolUtil.isNotEmpty(contacter)) {
                projectinfo.setContacter(contacter);
            }
            if (ToolUtil.isNotEmpty(phone)) {
                projectinfo.setPhone(phone);
            }
            if (ToolUtil.isNotEmpty(conunit)) {
                projectinfo.setConunit(conunit);
            }
            if (ToolUtil.isNotEmpty(totaluinit)) {
                projectinfo.setTotaluinit(totaluinit);
            }
            if (ToolUtil.isNotEmpty(overview)) {
                projectinfo.setOverview(overview);
            }
            if (ToolUtil.isNotEmpty(viewmark)) {
                projectinfo.setViewmark(viewmark);
            }
            if (ToolUtil.isNotEmpty(quantity)) {
                projectinfo.setQuantity(quantity);
            }
            if (ToolUtil.isNotEmpty(isannex)) {
                projectinfo.setIsannex(Integer.parseInt(isannex));
            }
            if (ToolUtil.isNotEmpty(projectremark)) {
                projectinfo.setProjectremark(projectremark);
            }
            if (ToolUtil.isNotEmpty(submitterphone)) {
                projectinfo.setSubmitterphone(submitterphone);
            }
            if (ToolUtil.isNotEmpty(bankcode)) {
                projectinfo.setBankcode(bankcode);
            }
            if (ToolUtil.isNotEmpty(bankname)) {
                projectinfo.setBankname(bankname);
            }
            if (ToolUtil.isNotEmpty(cardholder)) {
                projectinfo.setCardholder(cardholder);
            }
            if (ToolUtil.isNotEmpty(alipay)) {
                projectinfo.setAlipay(alipay);
            }
            if (ToolUtil.isNotEmpty(alipayname)) {
                projectinfo.setAlipayname(alipayname);
            }
            if (ToolUtil.isNotEmpty(wechat)) {
                projectinfo.setWechat(wechat);
            }
            projectinfo.setSubtime(new Date());
            projectinfoService.insert(projectinfo);
            Weixin weixin = new Weixin();
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.setEntity(new Wxuserinfo());
            entityWrapper.eq("isstaff", 1).eq("subscribe", 1);
            List<Wxuserinfo> wxuserinfos = wxuserinfoService.selectList(entityWrapper);

            for (int i = 0; i < wxuserinfos.size(); i++) {
                List<TemplateData> templateDataList = new ArrayList<>();
                TemplateData templateData = new TemplateData();
                templateData.setColor("red");
                templateData.setValue("您有新的项目提交，请及时处理!");
                templateData.setKey("first");
                templateDataList.add(templateData);
                TemplateData templateData1 = new TemplateData();
                templateData1.setColor("");
                templateData1.setValue(projectinfo.getContacter());
                templateData1.setKey("keyword1");
                templateDataList.add(templateData1);
                TemplateData templateData2 = new TemplateData();
                templateData2.setColor("");
                templateData2.setValue(projectinfo.getPhone());
                templateData2.setKey("keyword2");
                templateDataList.add(templateData2);
                TemplateData templateData3 = new TemplateData();
                templateData3.setColor("");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String audittime = df.format(new Date());
                templateData3.setValue(audittime);
                templateData3.setKey("keyword3");
                templateDataList.add(templateData3);
                TemplateData templateData4 = new TemplateData();
                templateData4.setColor("");
                templateData4.setValue("项目名称：" + projectinfo.getProjectname());
                templateData4.setKey("remark");
                templateDataList.add(templateData4);

                if (ToolUtil.isNotEmpty(wxuserinfos.get(i).getOpenid())) {
                    try {
                        weixin.message().sendTemplateMessage(wxuserinfos.get(i).getOpenid(), "pjmhT5TA4KMt8zDN75S2eJAJEK_U3YJbHB2leQIAIbw", templateDataList, "http://www.ynyxgcxx.com/inquier?id=" + projectinfo.getId() + "&wxuserinfoid=" + wxuserinfos.get(i).getId());
                    } catch (WeixinException e) {
                        e.printStackTrace();
                    }
                }
                //id，秘钥，电话，前缀，模板编号，发送信息
                String phonenum = wxuserinfos.get(i).getPhone();
                if (ToolUtil.isNotEmpty(phonenum)) {
                    try {
                        Common.sendMessage(accesskeyid, accesskeysecret, phonenum, "云南运祥", "SMS_146802795", "remark");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return SUCCESS;
        }
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail")
    @ResponseBody
    public Object detail(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        return projectinfoService.selectById(id);
    }

    /**
     * 审核
     */
    @RequestMapping(value = "/audit")
    @ResponseBody
    public Object audit(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        String status = mapTypes.getString("status");
        String money = mapTypes.getString("money");
        String remark = mapTypes.getString("remark");
        String auditremark = mapTypes.getString("auditremark");
        Projectinfo projectinfo = projectinfoService.selectById(id);
        projectinfo.setStatus(Integer.parseInt(status));
        projectinfo.setRemark(remark);
        projectinfo.setAuditremark(auditremark);
        if (ToolUtil.isNotEmpty(money)) {
            if (ToolUtil.isNum(money)) {
                projectinfo.setAuditmoney(new BigDecimal(money));
            }
        }
        projectinfo.setAudittime(new Date());
        projectinfoService.updateById(projectinfo);
        Weixin weixin = new Weixin();
        Wxuserinfo wxuserinfo = wxuserinfoService.selectOne(new EntityWrapper<Wxuserinfo>().eq("id", projectinfo.getCustomerid())
                .eq("subscribe", 1));
        if (projectinfo.getStatus() == 1) {
            List<TemplateData> templateDataList = new ArrayList<>();
            TemplateData templateData = new TemplateData();
            templateData.setColor("");
            templateData.setValue("您提交的项目已审核，请点击查看");
            templateData.setKey("first");
            templateDataList.add(templateData);
            TemplateData templateData1 = new TemplateData();
            templateData1.setColor("green");
            templateData1.setValue("通过");
            templateData1.setKey("keyword1");
            templateDataList.add(templateData1);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String audittime = df.format(new Date());
            TemplateData templateData2 = new TemplateData();
            templateData2.setColor("");
            templateData2.setValue(audittime);
            templateData2.setKey("keyword2");
            templateDataList.add(templateData2);
            TemplateData templateData3 = new TemplateData();
            templateData3.setColor("");
            templateData3.setValue("项目名称：" + projectinfo.getProjectname());
            templateData3.setKey("remark");
            templateDataList.add(templateData3);
            if (wxuserinfo != null) {
                try {
                    weixin.message().sendTemplateMessage(wxuserinfo.getOpenid(), "2qdoNTx7U5oXras8wAbgoJPFfSCH_N5VQ_k86HsAxBY", templateDataList, "http://www.ynyxgcxx.com/inquier?id=" + projectinfo.getId() + "&wxuserinfoid=" + wxuserinfo.getId());
                } catch (WeixinException e) {
                    e.printStackTrace();
                }
            }
        }
        if (projectinfo.getStatus() == 2) {
            List<TemplateData> templateDataList = new ArrayList<>();
            TemplateData templateData = new TemplateData();
            templateData.setColor("");
            templateData.setValue("您提交的项目已审核，请点击查看");
            templateData.setKey("first");
            templateDataList.add(templateData);
            TemplateData templateData1 = new TemplateData();
            templateData1.setColor("red");
            templateData1.setValue("未通过");
            templateData1.setKey("keyword1");
            templateDataList.add(templateData1);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String audittime = df.format(new Date());
            TemplateData templateData2 = new TemplateData();
            templateData2.setColor("");
            templateData2.setValue(audittime);
            templateData2.setKey("keyword2");
            templateDataList.add(templateData2);
            TemplateData templateData3 = new TemplateData();
            templateData3.setColor("");
            templateData3.setValue("项目名称：" + projectinfo.getProjectname());
            templateData3.setKey("remark");
            templateDataList.add(templateData3);
            if (wxuserinfo != null) {
                try {
                    weixin.message().sendTemplateMessage(wxuserinfo.getOpenid(), "2qdoNTx7U5oXras8wAbgoJPFfSCH_N5VQ_k86HsAxBY", templateDataList, "http://www.ynyxgcxx.com/inquier?id=" + projectinfo.getId() + "&wxuserinfoid=" + wxuserinfo.getId());
                } catch (WeixinException e) {
                    e.printStackTrace();
                }
            }
        }
        return SUCCESS;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        String id = mapTypes.getString("id");
        Projectinfo projectinfo = projectinfoService.selectById(id);
        if (projectinfo != null) {
            projectinfoService.deleteById(projectinfo.getId());
        }
        return SUCCESS;
    }

    /**
     * 获取公司信息
     */
    @RequestMapping(value = "/company")
    @ResponseBody
    public Object getinfo(@RequestBody String simpleObject) {
        JSONObject mapTypes = JSON.parseObject(simpleObject);
        EntityWrapper ew = new EntityWrapper();
        ew.where("isdefault = 0");
        return companyService.selectOne(ew);
    }
}
